package com.ruoyi.common.utils.pay;

import com.alipay.api.*;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.ruoyi.common.config.PayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@Component
public class AlipayUtil {

    private static PayConfig payConfig;

    @Autowired
    public void setPayConfig(PayConfig payConfig) {
        AlipayUtil.payConfig = payConfig;

    }

    private AlipayClient getAlipayClient() throws AlipayApiException {
        AlipayConfig config = new AlipayConfig();
        config.setAppId(payConfig.getAli_app_id());
        config.setPrivateKey(payConfig.getAli_private_key());
        config.setAlipayPublicKey(payConfig.getAli_public_key());

        return new DefaultAlipayClient(config);
    }

    /**
     * 支付宝支付-生成订单,(公钥模式)
     */
    public String createOrder(String outTradeNo, BigDecimal amount) {
//        String APP_ID = "2021000119665818";
//        String APP_PRIVATE_KEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCXW/ULgHVlKJWd4KzfwF1AsqD3A+s8Ucyr5Kp6oEqdEctu+DxO4LnrPimfAleEap6YvUuhjZj4MND0eJqJxYzFn9OBEwaBIWrzLpkTOBiIJkflasmhi3foCCdPqvEL23Bm6QJ6x91x8uEBidrzr3wVheesfzJhBazu3W80vw8xDdUe6nqvXCUzzqrMoeCultD7kOd7xftBAoO0WsQMwzvZ8JvwX6oTLZmYSQg8ZPmkXEbv3qv73XR+Io/Li4EmhRx68jM5g7eXv9DhdNGPHAufzTJHu0bYBbMOzl6jTU/HY70Uz+13VntSaqJrFXVkqUJN4ZTyhktbwlqCTshfdCOnAgMBAAECggEAVE6MN1PeD/KDI+U5ZYgoaRkWP4CXTonhjv1XV+ZgqQx4W984+FaEOFvvovoS9VbN8B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3aR1RCWUjEND43/WfeUelMFVCtVicpwr8crO6PEhvFY+razLn+jfQA2fKj4N+FYgN3uA==";
//        String CHARSET = "GBK";
//        String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq+PPNWsKLxpPU7xoq2cf7ZY7nNckpGBCSEhLZkuQcX3i0WOsN2b/RZomNlj6vlOvvMEnbfFP1g2EMYcvdvdd2RyD3qlMabCowbzseewPVPXjNZ6YBAPd8EBr/Cz7i1zQnVqBSf0Cn3L4L43/20g7O7BpP8TZe0whu6EA9g2HtkMt9hosQQEaGDCRBFpQiGDFs9nl8Z6OtPL73IYnsud8ZaFZt5Va3MI2+KU9q5G/uCgsvvV8mPojnZ54JCVFGMpsWFFvyCW52XN2JMKeYztnd0+o9e2AFZALkecbiST6UkXIHfXDX2tmZR/VhtKc+fXjfVKyOVMIcCJTys7nS6THvwIDAQAB";
////        String outtradeno = System.currentTimeMillis()+"";
//        String result = "";
        //实例化客户端
        //AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", APP_ID, APP_PRIVATE_KEY, "json", CHARSET, ALIPAY_PUBLIC_KEY, "RSA2");
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody("支付宝支付-下单");
        model.setSubject("购买会员");
        model.setOutTradeNo(outTradeNo);//订单号
        model.setTimeoutExpress("30m");
        model.setTotalAmount(amount.toEngineeringString());
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl(payConfig.getAli_notify_url()); //支付宝服务器主动通知商户服务器里指定的页面http/https路径。
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = getAlipayClient().sdkExecute(request);
            if (!response.isSuccess())
                throw new RuntimeException("支付宝支付调用失败=>" + response.getMsg());

            return response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 支付宝支付-生成订单,(证书模式)
     */
    public String createOrder2() {

        String orderstr = "";
        String app_id = "";
        String privateKey = "";
        String charset = "";
        String sign_type = "";
        String app_cert_path = "";
        String alipay_cert_path = "";
        String alipay_root_cert_path = "";
        String outtradeno = System.currentTimeMillis() + "";
        //构造client
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        //设置网关地址
        certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
        //设置应用Id
        certAlipayRequest.setAppId(app_id);
        //设置应用私钥
        certAlipayRequest.setPrivateKey(privateKey);
        //设置请求格式，固定值json
        certAlipayRequest.setFormat("json");
        //设置字符集
        certAlipayRequest.setCharset(charset);
        //设置签名类型
        certAlipayRequest.setSignType(sign_type);
        //设置应用公钥证书路径
        certAlipayRequest.setCertPath(app_cert_path);
        //设置支付宝公钥证书路径
        certAlipayRequest.setAlipayPublicCertPath(alipay_cert_path);
        //设置支付宝根证书路径
        certAlipayRequest.setRootCertPath(alipay_root_cert_path);
        //构造client
        AlipayClient alipayClient = null;
        try {
            alipayClient = new DefaultAlipayClient(certAlipayRequest);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody("我是测试数据");
        model.setSubject("App支付测试Java");
        model.setOutTradeNo(outtradeno);
        model.setTimeoutExpress("30m");
        model.setTotalAmount("0.01");
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl("商户外网可以访问的异步地址");
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            orderstr = response.getBody();
            System.out.println(response.getBody()); //就是orderString 可以直接给客户端请求，无需再做处理。
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return orderstr;
    }

    /**
     * 沙箱环境支付测试
     *
     * @return
     */
    public static String sandboxOrder(String amount, String subject) {
        String qrcode = "";
        String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq+PPNWsKLxpPU7xoq2cf7ZY7nNckpGBCSEhLZkuQcX3i0WOsN2b/RZomNlj6vlOvvMEnbfFP1g2EMYcvdvdd2RyD3qlMabCowbzseewPVPXjNZ6YBAPd8EBr/Cz7i1zQnVqBSf0Cn3L4L43/20g7O7BpP8TZe0whu6EA9g2HtkMt9hosQQEaGDCRBFpQiGDFs9nl8Z6OtPL73IYnsud8ZaFZt5Va3MI2+KU9q5G/uCgsvvV8mPojnZ54JCVFGMpsWFFvyCW52XN2JMKeYztnd0+o9e2AFZALkecbiST6UkXIHfXDX2tmZR/VhtKc+fXjfVKyOVMIcCJTys7nS6THvwIDAQAB";
        String privateKey = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCXW/ULgHVlKJWd4KzfwF1AsqD3A+s8Ucyr5Kp6oEqdEctu+DxO4LnrPimfAleEap6YvUuhjZj4MND0eJqJxYzFn9OBEwaBIWrzLpkTOBiIJkflasmhi3foCCdPqvEL23Bm6QJ6x91x8uEBidrzr3wVheesfzJhBazu3W80vw8xDdUe6nqvXCUzzqrMoeCultD7kOd7xftBAoO0WsQMwzvZ8JvwX6oTLZmYSQg8ZPmkXEbv3qv73XR+Io/Li4EmhRx68jM5g7eXv9DhdNGPHAufzTJHu0bYBbMOzl6jTU/HY70Uz+13VntSaqJrFXVkqUJN4ZTyhktbwlqCTshfdC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ntma2uVv/gx1XffJzwsJ04xpMb8pqES/opon+zWmYAciA/r6wqnoYB80LyPjKrSZvn4dzidhZ3LZvToESiup7reo3aR1RCWUjEND43/WfeUelMFVCtVicpwr8crO6PEhvFY+razLn+jfQA2fKj4N+FYgN3uA==";
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do", "2021000119665818", privateKey, "json", "utf-8", publicKey, "RSA2");
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        request.setBizModel(model);
        model.setOutTradeNo(System.currentTimeMillis() + "");
        model.setTotalAmount(amount);
        model.setSubject(subject);
        AlipayTradePrecreateResponse response = null;
        try {
            response = alipayClient.execute(request);
            qrcode = response.getQrCode();
            System.out.print(response.getBody());
            System.out.print(response.getQrCode());
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }


        return qrcode;
    }

}
